package com.wl.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wl.response.CommonReturnType;
import lombok.SneakyThrows;
import org.junit.Test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 工具类
 *
 * @program: treeHole
 * @author: 吴磊
 * @create: 2021-07-06 18:32
 */
public class MyUtil {
    /**
     * 返回一个随机的String类型的时间
     *
     * @return
     */
    public static String getRandomStringTime() {
        Random random = new Random();
        int year = random.nextInt(11) + 2011;
        int month = random.nextInt(7) + 1;
        int day = random.nextInt(28) + 1;
        int hour = random.nextInt(24);
        int minute = random.nextInt(60);
        int s = random.nextInt(60);
        String time = year + "-" +
                (("" + month).length() < 2 ? "0" + month : month) + "-" +
                (("" + day).length() < 2 ? "0" + day : day) + " " +
                (("" + hour).length() < 2 ? "0" + hour : hour) + ":" +
                (("" + minute).length() < 2 ? "0" + minute : minute) + ":" +
                (("" + s).length() < 2 ? "0" + s : s);
        return time;
    }

    @Test
    public void test1() {
        for (int i = 0; i < 100; i++) {
            System.out.println(getRandomStringTime());
        }
    }

    /**
     * 返回一个UUID
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 获取当前时间（2021-11-11 11:11:11）
     *
     * @return
     */
    public static String getCurrentDetailedTime() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    /**
     * 将String类型的时间转化成long型的时间戳
     *
     * @param date
     * @return
     */
    @SneakyThrows
    public static long parseTimeToString(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = format.parse(date);
        return d.getTime();
    }

    /**
     * 将Date类型的时间转化成String类型的时间
     *
     * @param date
     * @return
     */
    public static String parseTimeToString(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;
    }

    /**
     * 将Long类型的时间转化成String类型的时间
     *
     * @param l
     * @return
     */
    public static String parseLongTimeToString(Long l) {
        Date date = new Date(l);
        return parseTimeToString(date);
    }


    /**
     * 将一个结果集转化成Bean
     *
     * @param clazz
     * @param map
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T convertMapToBean(Class<T> clazz, Map<String, String> map) throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        T target = clazz.newInstance();
        for (String key : map.keySet()) {
            if ("serialVersionUID".equals(key)) {
                continue;
            }
            String value = map.get(key);
            for (Field field : fields) {
                String name = field.getName();
                if (name.equalsIgnoreCase(key)) {
                    field.setAccessible(true);
                    String typeName = field.getType().getName();
                    if ("int".equals(typeName) || "java.lang.Integer".equals(typeName)) {
                        field.set(target, Integer.parseInt(value));
                    } else if ("double".equals(typeName) || "java.lang.Double".equals(typeName)) {
                        field.set(target, Double.parseDouble(value));
                    } else if ("float".equals(typeName) || "java.lang.Float".equals(typeName)) {
                        field.set(target, Float.parseFloat(value));
                    } else if ("long".equals(typeName) || "java.lang.Long".equals(typeName)) {
                        field.set(target, Long.parseLong(value));
                    } else if ("short".equals(typeName) || "java.lang.Short".equals(typeName)) {
                        field.set(target, Short.parseShort(value));
                    } else if ("char".equals(typeName) || "java.lang.Character".equals(typeName)) {
                        field.set(target, value.charAt(0));
                    } else if ("date".equals(typeName) || ("java.util.Date").equals(typeName)) {
                        field.set(target, new Date(value));
                    } else if (("java.math.BigDecimal").equals(typeName)) {
                        field.set(target, new BigDecimal(value));
                    } else {
                        field.set(target, value);
                    }
                    break;
                }
            }
        }
        return target;
    }

    /**
     * 从请求中获取参数并封装
     *
     * @param clazz
     * @param request
     * @param <T>
     * @return
     */
    public static <T> T getTFromRequest(Class<T> clazz, HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        HashMap<String, String> result = new HashMap<>();
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            String[] values = entry.getValue();
            if (values == null || values.length <= 0) {
                continue;
            }
            result.put(entry.getKey(), values[0]);
        }
        T target = null;
        try {
            target = MyUtil.convertMapToBean(clazz, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return target;
    }

    /**
     * 返回数据给前端
     *
     * @param response
     * @param commonReturnType
     * @throws IOException
     */
    @SneakyThrows
    public static void responseData(HttpServletResponse response, CommonReturnType commonReturnType) {
        String jsonString = JSON.toJSONString(commonReturnType, SerializerFeature.DisableCircularReferenceDetect);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(jsonString);
        out.flush();
        out.close();
    }
}
